package cn.cheneyjoo.config;

import cn.cheneyjoo.model.Configuration;
import cn.cheneyjoo.model.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parseMapper(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        List<Element> nodes = rootElement.selectNodes("//select");
        nodes.addAll(rootElement.selectNodes("//insert"));
        nodes.addAll(rootElement.selectNodes("//update"));
        nodes.addAll(rootElement.selectNodes("//delete"));
        String namespace = rootElement.attributeValue("namespace");
        for (Element node : nodes) {
            String sqlType = node.getName();
            String id = node.attributeValue("id");
            String resultType = node.attributeValue("resultType");
            String parameterType = node.attributeValue("parameterType");
            String sqlText = node.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setSqlType(sqlType);
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setSqlText(sqlText);
            configuration.getMappedStatementMap().put(namespace + "." + id, mappedStatement);
        }
    }
}
